package hanqi.llbrary.Controller;

import hanqi.llbrary.Service.PublisherService;
import hanqi.llbrary.Service.bookService;
import hanqi.llbrary.entity.book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/book")
public class BookController {
  @Autowired
  private bookService bookService;
  @Autowired
  private PublisherService publisherService;
  @GetMapping("/bookList")
  public ModelAndView bookList() {
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("bookList");
  modelAndView.addObject("books", bookService.findAll());
  modelAndView.addObject("publishers", publisherService.findAll());
  return modelAndView;
  }
  @GetMapping("/findById/{id}")
  public ModelAndView findById(@PathVariable Long id) {
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.addObject("book", bookService.findById(id));
  modelAndView.setViewName("BookEditor");
  modelAndView.addObject("publishers", publisherService.findAll());
  return modelAndView;
  }
  @PostMapping("/save")
  public String save(book book, @RequestParam Integer publisherId) {
  book.setPublisher(publisherService.getById(publisherId));
  bookService.save(book);
  return "redirect:/book/bookList";
  }
  //根据id删除数据库的记录
         @GetMapping("/delete/{id}")
  public String deleteById(@PathVariable Long id) {
  bookService.deleteById(id);
  return "redirect:/book/bookList";
  }
  @PostMapping("/update")
  public String updateById(book book, @RequestParam Integer publisherId) {
  book.setPublisher(publisherService.getById(publisherId));
  bookService.update(book);
  return "redirect:/book/bookList";
  }
  @GetMapping("/SearchList")
  public ModelAndView SearchList(@RequestParam String searchName) {
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("bookList");
  modelAndView.addObject("books", bookService.findByTitle(searchName));
  return modelAndView;
  }
  @GetMapping("/AuthorList")
  public ModelAndView AuthorList() {
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("authorList");
  modelAndView.addObject("authors", bookService.findAuthorList());
  return modelAndView;
  }
  }